<template>
  <div class="content">
    <div class="content-head">
      <el-form :inline="true" :model="formData" label-position="left">
        <el-form-item label="选择日期" label-width="70px" class="form-item">
          <el-date-picker v-model="formData.startAndEndDate" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" size="mini" :clearable="false" style="width:220px;"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" icon="el-icon-refresh-left" @click="reset_btn">重置</el-button>
          <el-button type="success" size="mini" icon="el-icon-search" @click="search_btn">查询</el-button>
          <el-button type="info" size="mini" icon="el-icon-download" :loading="exportBtnLoading" @click="export_btn">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="content-table">
      <div class="table-info">生产计件报表</div>
      <el-table :data="tableData" v-loading="tableLoading" style="width: 100%;" :max-height="tableMaxHeight" border class="content-table-item">
        <el-table-column prop="reportTime" label="日期" width="150" align="center"></el-table-column>
        <el-table-column prop="workShop" label="车间" width="150" align="center">
          <template slot-scope="scope" slot="header">
            <table-head-filter label="车间" type="input" :bindData="formData.workShop" filterField="workShop" @change="filterChangeEvent"></table-head-filter>
          </template>
        </el-table-column>
        <el-table-column prop="classes" label="班次" width="150" align="center">
          <template slot-scope="scope" slot="header">
            <table-head-filter label="班次" type="input" :bindData="formData.classes" filterField="classes" @change="filterChangeEvent"></table-head-filter>
          </template>
        </el-table-column>
        <el-table-column prop="equipmentType" label="设备类型" width="150" align="center">
          <template slot-scope="scope" slot="header">
            <table-head-filter label="设备类型" type="input" :bindData="formData.equipmentType" filterField="equipmentType" @change="filterChangeEvent"></table-head-filter>
          </template>
        </el-table-column>
        <el-table-column prop="productNumber" label="生产订单" width="150" align="center"></el-table-column>
        <el-table-column prop="machineCode" label="设备编号" width="150" align="center"></el-table-column>
        <el-table-column prop="productCode" label="产品编码" width="150" align="center">
          <template slot-scope="scope" slot="header">
            <table-head-filter label="产品编码" type="input" :bindData="formData.productCode" filterField="productCode" @change="filterChangeEvent"></table-head-filter>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称" width="150" align="center"></el-table-column>
        <el-table-column prop="attendanceHours" label="工时" width="150" align="center"></el-table-column>
        <el-table-column prop="workingHours" label="设备运行时长" width="150" align="center"></el-table-column>
        <el-table-column prop="actualOutput" label="实际产出" width="150" align="center"></el-table-column>
        <!-- <el-table-column prop="" label="理论工时" width="150" align="center"></el-table-column>
        <el-table-column prop="" label="实际工时" width="150" align="center"></el-table-column> -->
        <el-table-column prop="targetUnitCost" label="工价" width="150" align="center"></el-table-column>
        <el-table-column prop="qualifiedQuantity" label="报工合格数量" width="150" align="center"></el-table-column>
        <el-table-column prop="valuationWage" label="计件工资" width="150" align="center"></el-table-column>
        <el-table-column prop="laborCostQuantity" label="工废数量" width="150" align="center"></el-table-column>
        <el-table-column prop="scrapMoney" label="废件费用" width="150" align="center"></el-table-column>
        <el-table-column prop="pieceworkDeduction" label="计件扣款" width="150" align="center"></el-table-column>
        <el-table-column prop="materialScrapQuantity" label="料废数量" width="150" align="center"></el-table-column>
        <el-table-column prop="materialScrapReward" label="料废奖励" width="150" align="center"></el-table-column>
        <el-table-column prop="payableWage" label="应付工资" width="150" align="center"></el-table-column>
        <el-table-column prop="operator" label="操作人员" width="150" align="center"></el-table-column>
      </el-table>
    </div>
    <div class="content-footer">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10,20,30,50,100,200]" :page-size="pageSize" background layout="prev, pager, next,total, sizes, jumper" :total="total"></el-pagination>
    </div>
  </div>
</template>
  
<script>
import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
import TableHeadFilter from "@/components/tableHeadFilter/index.vue";
import { reqProductionPieceworkReport,reqProductionPieceworkReportExport } from "@/api/workOrder.js";

export default {
  name:"productionPieceworkReport",  //生产计件报表
  components:{
    TableHeadFilter
  },
  data() {
    return {
      formData:{
        startAndEndDate:[this.formatDate(null,1),this.formatDate(null,1)],
        workShop:"",
        classes:"",
        equipmentType:"",
        productCode:""
      },
      tableData:[],
      tableLoading:false,
      tableMaxHeight:450,
      currentPage:1,
      pageSize:20,
      total:0,
      exportBtnLoading:false
    }
  },
  mounted(){
    this.getProductionPieceworkReport();
    //精致环境下进行自动旋转
    //autoOrientation();
    this.calculateTableMaxHeight();
    document.title = "生产计件报表";
    window.addEventListener("resize", this.calculateTableMaxHeight);
  },
  beforeDestroy(){
    window.removeEventListener("resize", this.calculateTableMaxHeight);
  },
  methods:{
    getProductionPieceworkReport(){
      const { startAndEndDate,workShop,classes,equipmentType,productCode } = this.formData;
      const parameter = { page:this.currentPage,size:this.pageSize,startDate:startAndEndDate[0],endDate:startAndEndDate[1],workShop,classes,equipmentType,productCode };
      this.tableLoading = true;
      reqProductionPieceworkReport(parameter).then(response => {
        if(response.data.code === 200){
          this.tableData = response.data.data.content;
          this.total = response.data.data.totalElements;
        }
        console.log('获取生产计件报表api',response);
        this.tableLoading = false;
      }).catch(error => {
        this.$message.error("生产计件列表数据获取失败");
        console.log('获取生产计件报表api',error);
        this.tableLoading = false;
      })
    },
    reset_btn(){
      this.formData.startAndEndDate = [this.formatDate(null,1),this.formatDate(null,1)];
      this.getProductionPieceworkReport();
    },
    search_btn(){
      const { startAndEndDate } = this.formData;
      if(startAndEndDate.length !== 2){
        this.$message({type:"warning",message:"选择起始日期后进行查询"});
        return;
      }
      this.getProductionPieceworkReport();
    },
    export_btn() {
      const { startAndEndDate } = this.formData;
      const parameters = { startDate:startAndEndDate[0],endDate:startAndEndDate[1] };
      this.$confirm('即将导出当前内容,数据将根据筛选条件进行过滤', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'})
        .then(async () => {
            this.exportBtnLoading = true;
            let res = await reqProductionPieceworkReportExport(parameters);
            if (res.status === 200) {
              let blob = res.data;
              let url = window.URL.createObjectURL(blob,{type: 'application/zip'});
              const aLink = document.createElement('a');
              aLink.href = url;
              let timestamp = new Date().getTime();
              aLink.setAttribute('download', '生产计件报表_' + timestamp);
              document.body.appendChild(aLink);
              aLink.click();
              document.body.removeChild(aLink);
              this.$message.success('导出成功');
              this.exportBtnLoading = false;
            } else {
              const errMsg = res.data?.message || '导出失败,请重试';
              this.$message.error(errMsg);
              this.exportBtnLoading = false;
            }
        }).catch(() => {
          this.exportBtnLoading = false;
          this.$message({type: 'info', message: '已取消导出!'});          
        });
    },
    //分页器
    handleCurrentChange(curPage){
      this.currentPage = curPage;
      this.getProductionPieceworkReport();
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize;
      this.getProductionPieceworkReport();
    },
    //格式化时间
    formatDate(val,type){
      let date = null;
      val === null ? date = new Date() : date = new Date(val);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let h = date.getHours();
      let m = date.getMinutes();
      let s = date.getSeconds();
      if(type === 0){
          return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
      } else if (type === 1){
          return year + "-" + this.addZero(month) + "-" + this.addZero(day);
      } else if (type === 2){
          return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
      } else if (type === 3){
          return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
      }
    },
    addZero(val){
        return val > 9 ? val : "0" + val;
    },
    calculateTableMaxHeight(){
      const dom = document.querySelector(".content-table");
      this.$nextTick(() => {
        this.tableMaxHeight = dom.offsetHeight - 30;
      })
    },
    //tableHeadFiler的change事件
    filterChangeEvent(parameter){
      const { state, filterField, selectedValue } = parameter;
      if(state === 'clear'){
        //清空操作
        if(this.formData[filterField] !== ""){
          this.formData[filterField] = "";
          this.getProductionPieceworkReport();
        }
      }
      if(state === 'confirm'){
        //确定操作
        this.formData[filterField] = selectedValue;
        if(selectedValue !== ""){
          this.getProductionPieceworkReport();
        }
      }
    }
  }
}
</script>

<style lang='scss' scoped>
  .content{
    width: 100%;
    height: 100%;
    padding: 5px;
    box-sizing: border-box;
  
    .content-head{
      width:100%;
      height:50px;
    }
    .content-table{
      width:100%;
      height:calc(100% - 50px - 50px);
      .table-info{
        width:100%;
        height: 30px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        font-size: 16px;
        color:#9195a3;
      }
    }
    .content-footer{
      width:100%;
      height:50px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }
  </style>